// pages/clients/clients.js
import http from '../../utils/request';  // ✅ 改用封装后的请求模块

Page({
    data: {
      ranking: [],
      fullList: [],
      showFullIndex: -1,
      loading: true,
      employeeNumber: ''
    },
  
    // ====================== 生命周期方法 ======================
    onShow() {
      this.checkLoginStatus();
    },
  
    // ====================== 登录状态检查 ======================
    checkLoginStatus() {
      try {
        const userInfo = wx.getStorageSync('userInfo');
        if (!userInfo?.employee_number) {
          this.showLoginAlert();
          return;
        }
  
        this.setData({
          employeeNumber: userInfo.employee_number.trim()
        }, () => this.loadCustomerData());
        
      } catch (error) {
        console.error('存储读取失败:', error);
        this.showLoginAlert();
      }
    },

    // ====================== 数据加载接口改造 ======================
    async loadCustomerData() {
      if (!this.data.employeeNumber) return;
  
      wx.showLoading({ title: '加载中...' });
      
      try {
        // ============== 接口改造开始 ==============
        const res = await http.get('/client_summary', {
          employee_number: this.data.employeeNumber
        });
        // ============== 接口改造结束 ==============

        console.log('[DEBUG] 原始接口响应:', res);

        // ✅ 适配新的响应结构
        if (res?.status !== 'success' || !res.data) {
          throw new Error(res?.message || '数据加载失败');
        }

        const apiData = res.data;
        console.log('[DEBUG] 处理后数据:', apiData);
        
        // 处理前三名数据（保留原有注释）
        const ranking = (apiData.ranking || []).slice(0, 3).map(item => ({
          ...item,
          formattedAmount: this._formatAmount(item.total_amount || item.amount),
          formattedPhone: this._formatPhone(item.phone),
          originalPhone: item.phone
        }));
  
        // 处理剩余客户数据（从第四名开始）（保留原有注释）
        const remainingList = (apiData.full_list || [])
          .slice(3)
          .map((item, index) => ({
            ...item,
            id: index + 4, // ID从4开始
            formattedAmount: this._formatAmount(item.total_amount || item.amount),
            formattedPhone: this._formatPhone(item.phone),
            originalPhone: item.phone,
            showFull: false
          }));
  
        this.setData({
          ranking,
          fullList: remainingList, // 仅包含第四名及之后的客户
          loading: false
        });
  
      } catch (error) {
        console.error('数据加载失败:', error);
        wx.showToast({ 
          title: error.message,
          icon: 'none',
          duration: 3000
        });
        this.setData({ loading: false });
      } finally {
        wx.hideLoading();
      }
    },
  
    // ====================== 数据格式化方法 ======================
    _formatAmount(amount) {
      // 增强数值处理逻辑（保留原有注释）
      const num = typeof amount === 'number' ? amount : parseFloat(amount) || 0;
      return num.toLocaleString('zh-CN', { 
        style: 'currency', 
        currency: 'CNY',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    },
  
    _formatPhone(phone) {
      const clean = String(phone || '').replace(/\D/g, '');
      return clean.length >= 7 
        ? `${clean.slice(0,3)}****${clean.slice(-4)}` 
        : '未知号码';
    },

    // ====================== 交互方法 ======================
    togglePhone(e) {
      const index = e.currentTarget.dataset.index;
      const phone = this.data.ranking[index].originalPhone;
      wx.showModal({
        title: '完整号码',
        content: phone || '号码不存在',
        showCancel: false,
        confirmText: '关闭'
      });
    },
  
    toggleListPhone(e) {
      const index = e.currentTarget.dataset.index;
      const phone = this.data.fullList[index].originalPhone;
      wx.showModal({
        title: '完整号码',
        content: phone || '号码不存在',
        showCancel: false,
        confirmText: '关闭'
      });
    },
  
    // ====================== 登录提示 ======================
    showLoginAlert() {
        wx.showModal({
          title: '未登录',
          content: '请先登录后再使用该功能',
          confirmText: '去登录',
          cancelText: '返回首页', // 明确提示取消操作的含义
          success: (res) => {
            if (res.confirm) {
              wx.reLaunch({ url: '/pages/user/user' });
            } else if (res.cancel) {
              // 增加页面堆栈判断防止报错
              if (getCurrentPages().length > 1) {
                wx.navigateBack({ delta: 1 }); // 返回上一页
              } else {
                wx.reLaunch({ url: '/pages/home/home' }); // 无上一页时回首页
              }
            }
          },
          fail: (err) => {
            console.error('弹窗调用失败:', err);
          }
        });
      },

    // ====================== 跳转搜索页 ======================
    openSearch() {
      wx.navigateTo({
        url: `/pages/search/search?employeeNumber=${this.data.employeeNumber}`,
        success: () => {
          this.setData({ showMask: true }) // 可选：添加遮罩层
        }
      })
    }
});